BUILD_DIR ?= $(error BUILD_DIR not set)

VERILATOR_FLAGS := -I$(BUILD_DIR)/gen -I. +define+USE_GENERIC_LIB
VERILATOR_OUTPUT_DIR := $(BUILD_DIR)/verilated

.PHONY: all
all: compile

.PHONY: system
system:
	mkdir -p $(BUILD_DIR)/gen
	cd ocaml; corebuild -I common -build-dir $(BUILD_DIR) cpugen/cpugen.native
	cd $(BUILD_DIR); python3 $(CURDIR)/gen_decode.py $(CURDIR)/decode.ini
	cat $(BUILD_DIR)/gen/encoding datapath | $(BUILD_DIR)/cpugen/cpugen.native -o $(BUILD_DIR)/gen -I . -I $(BUILD_DIR)/gen

.PHONY: lint
lint:
	verilator --lint-only -Wall $(VERILATOR_FLAGS) system.v

.PHONY: compile
compile: system
	verilator --cc $(VERILATOR_FLAGS) --trace system.v --exe $(CURDIR)/tb.cpp -Mdir $(VERILATOR_OUTPUT_DIR)
	$(MAKE) -C $(VERILATOR_OUTPUT_DIR) -f Vsystem.mk

.PHONY: run
run:
	$(VERILATOR_OUTPUT_DIR)/Vsystem $(MEMFILE)

.PHONY: test
test: all
	./run -a
